package controller

import (
	"gitee.com/wang-xiangyu20000112/vblog/apps/user/po"
	"gitee.com/wang-xiangyu20000112/vblog/apps/user/service/impl"
	"gitee.com/wang-xiangyu20000112/vblog/apps/user/vo"
	"gitee.com/wang-xiangyu20000112/vblog/comment"
	"gitee.com/wang-xiangyu20000112/vblog/logger"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

var (
	userService *impl.UserServiceImpl
	response    *comment.Result
)

// 添加用户
func AddUser(c *gin.Context) {
	var userVo = &vo.UserVo{User: &po.User{}}
	// 获取请求体封装进入userVo对象
	err := c.ShouldBind(userVo)
	// 输出日志
	logger.ZapLogger.Info("AddUser", zap.Any("userVo", userVo))
	if err != nil {
		logger.ZapLogger.Error("AddUser -> 参数解析失败", zap.Any("err", err))
		c.JSON(http.StatusInternalServerError, response.Fail(
			"参数解析失败", http.StatusInternalServerError,
			err,
		))
		return
	}
	// 调用Service添加用户
	result := userService.InsertUser(c, userVo)
	// 输出日志
	logger.ZapLogger.Info("AddUser", zap.Any("result", result))

	// 返回结果
	c.JSON(http.StatusOK, result)
}

// 查询用户
func GetUserById(c *gin.Context) {
	// 获取路径参数
	id, exists := c.GetQuery("id")
	// 输出日志
	logger.ZapLogger.Info("GetUserById", zap.Any("id", id))
	// 判断参数是否为空
	if !exists {
		logger.ZapLogger.Error("GetUserById", zap.String("err", "参数为空"))
		c.JSON(http.StatusBadRequest, response.Fail(
			"参数为空", http.StatusBadRequest,
			exists,
		))
		return
	}
	// 查询用户
	result := userService.FindUserById(c, id)
	// 输出日志
	logger.ZapLogger.Info("GetUserById", zap.Any("result", result))

	c.JSON(http.StatusOK, result)
}

// 删除用户
func DeleteUser(c *gin.Context) {
	// 获取路径参数
	id := c.Param("id")
	// 输出日志
	logger.ZapLogger.Info("DeleteUser", zap.Any("id", id))
	if id == "nil" {
		logger.ZapLogger.Error("DeleteUser -> id为空")
		c.JSON(http.StatusBadRequest, response.Fail(
			"id为空", http.StatusBadRequest,
			nil,
		))
		return
	}
	// 封装请求对象
	atoi, _ := strconv.Atoi(id)
	userVo := vo.UserVo{User: &po.User{ID: atoi}}
	// 调用Service删除用户
	result := userService.DeleteUser(c, &userVo)
	// 输出日志
	logger.ZapLogger.Info("DeleteUser", zap.Any("result", result))

	// 返回结果
	c.JSON(http.StatusOK, result)
}

// 修改用户
func UpdateUser(c *gin.Context) {
	var userVo = new(vo.UserVo)
	// 获取请求体封装进入userVo对象
	err := c.ShouldBind(userVo)
	// 输出日志
	logger.ZapLogger.Info("UpdateUser", zap.Any("userVo", userVo))
	if err != nil {
		logger.ZapLogger.Error("UpdateUser -> 参数解析失败", zap.Any("err", err))
		c.JSON(http.StatusInternalServerError, response.Fail(
			"参数解析失败", http.StatusInternalServerError,
			err,
		))
		return
	}
	// 调用Service添加用户
	result := userService.UpdateUser(c, userVo)
	// 输出日志
	logger.ZapLogger.Info("UpdateUser", zap.Any("result", result))

	// 返回结果
	c.JSON(http.StatusOK, result)
}
